<?php

namespace app\user\controller\school\course;

use app\admin\service\ReportService;
use app\BaseController;
use app\model\not_del\UserModel;
use app\model\school\SchoolCourseChapterCommentModel;
use app\model\school\SchoolCourseChapterLearningModel;
use app\model\school\SchoolCourseChapterModel;
use app\model\school\SchoolCourseCollectModel;
use app\model\school\SchoolCourseModel;
use app\user\service\SchoolService;
use think\App;

class Index extends BaseController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 课程列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数量' => 'require',
            ]);
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseCollectModel = new SchoolCourseCollectModel();
            $SchoolCourseChapterCommentModel = new SchoolCourseChapterCommentModel();
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name|editor', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['is_learning']) && strlen($param['is_learning']) > 0) {
                $course_id = $SchoolCourseChapterLearningModel->where('uid', '=', $this->userData['id'])->column('course_id');
                if ($param['is_learning'] == 1) {
                    if (!empty($course_id)) {
                        $where[] = ['id', 'in', $course_id];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($course_id)) {
                        $where[] = ['id', 'not in', $course_id];
                    }
                }
            }
            if (!empty($param['is_collect']) && strlen($param['is_collect']) > 0) {
                $course_id = $SchoolCourseChapterCommentModel->where('uid', '=', $this->userData['id'])->column('course_id');
                if ($param['is_collect'] == 1) {
                    if (!empty($course_id)) {
                        $where[] = ['id', 'in', $course_id];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($course_id)) {
                        $where[] = ['id', 'not in', $course_id];
                    }
                }
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $data = $SchoolCourseModel->where($where)->withCount([
                'chapter'
            ])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$v) {
                $v['learning_num'] = $SchoolCourseChapterLearningModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->count();
                $is_collect = $SchoolCourseCollectModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->value('id');
                if ($is_collect) {
                    $v['is_collect'] = 1;
                } else {
                    $v['is_collect'] = 0;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 热门课程
     * @return bool|string
     */
    public function hot(): bool|string
    {
        try {
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseCollectModel = new SchoolCourseCollectModel();
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $data = $SchoolCourseModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['status', '=', 1]
            ])->withCount([
                'chapter'
            ])->order('study_num', 'desc')->limit(0, 4)->select()->toArray();
            foreach ($data as &$v) {
                $v['learning_num'] = $SchoolCourseChapterLearningModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->count();
                $is_collect = $SchoolCourseCollectModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->value('id');
                if ($is_collect) {
                    $v['is_collect'] = 1;
                } else {
                    $v['is_collect'] = 0;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 热门课程-手机端
     * @return bool|string
     */
    public function hot2(): bool|string
    {
        try {
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseCollectModel = new SchoolCourseCollectModel();
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $data = $SchoolCourseModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['status', '=', 1]
            ])->withCount([
                'chapter'
            ])->order('study_num', 'desc')->limit(0, 1)->select()->toArray();
            foreach ($data as &$v) {
                $v['learning_num'] = $SchoolCourseChapterLearningModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->count();
                $is_collect = $SchoolCourseCollectModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['course_id', '=', $v['id']]
                ])->value('id');
                if ($is_collect) {
                    $v['is_collect'] = 1;
                } else {
                    $v['is_collect'] = 0;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 学习课件
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $SchoolCourseModel = new SchoolCourseModel();
            $info = $SchoolCourseModel->with([
                'chapter' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            //收藏情况
            $SchoolCourseCollectModel = new SchoolCourseCollectModel();
            $is_collect = $SchoolCourseCollectModel->where([
                ['uid', '=', $this->userData['id']],
                ['course_id', '=', $param['id']]
            ])->value('id');
            if ($is_collect) {
                $info['is_collect'] = 1;
            } else {
                $info['is_collect'] = 0;
            }
            $info['learning_num'] = 0;
            //测评情况
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            foreach ($info['chapter'] as &$item) {
                $Learning = $SchoolCourseChapterLearningModel->where([
                    ['uid', '=', $this->userData['id']],
                    ['chapter_id', '=', $item['id']]
                ])->find();
                if ($Learning) {
                    $info['learning_num']++;
                    $item['is_learning'] = $Learning['is_learning'];
                    $item['is_finish'] = $Learning['is_finish'];
                    $item['result_id'] = $Learning['result_id'];
                    $item['learning'] = $Learning['learning'];
                } else {
                    $item['is_learning'] = 0;
                    $item['is_finish'] = 0;
                    $item['result_id'] = 0;
                    $item['learning'] = '';
                }
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 章节详情
     * @return bool|string
     */
    public function chapterInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $SchoolCourseChapterModel = new SchoolCourseChapterModel();
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $info = $SchoolCourseChapterModel->with(['RatingScale'])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $Learning = $SchoolCourseChapterLearningModel->where([
                ['uid', '=', $this->userData['id']],
                ['chapter_id', '=', $param['id']]
            ])->find();
            if ($Learning) {
                $info['is_learning'] = $Learning['is_learning'];
                $info['is_finish'] = $Learning['is_finish'];
                $info['result_id'] = $Learning['result_id'];
                $info['learning'] = $Learning['learning'];
            } else {
                $info['is_learning'] = 0;
                $info['is_finish'] = 0;
                $info['result_id'] = 0;
                $info['learning'] = '';
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 收藏
     * @return bool|string
     */
    public function collect(): bool|string
    {
        $SchoolCourseModel = new SchoolCourseModel();
        $SchoolCourseModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'status|状态' => 'require'
            ]);
            $info = $SchoolCourseModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $SchoolCourseCollectModel = new SchoolCourseCollectModel();
            switch ($param['status']) {
                case 0:
                    //取消收藏
                    $SchoolCourseCollectModel->where([
                        ['uid', '=', $this->userData['id']],
                        ['course_id', '=', $param['id']]
                    ])->delete();
                    $info->dec('collect_num');
                    break;
                case 1:
                    //收藏
                    $SchoolCourseCollectModel->insert([
                        'uid' => $this->userData['id'],
                        'course_id' => $param['id'],
                        'time' => time()
                    ]);
                    $info->inc('collect_num');
                    break;
            }
            $info->save();
            $SchoolCourseModel->commit();
            return success();
        } catch (\Exception $e) {
            $SchoolCourseModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 评论列表
     * @return bool|string
     */
    public function commentList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require'
            ]);
            $SchoolCourseChapterCommentModel = new SchoolCourseChapterCommentModel();
            $data = $SchoolCourseChapterCommentModel->where('chapter_id','=',$param['id'])->with([
                'user'
            ])->order('id','desc')->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 发送评论
     * @return bool|string
     */
    public function sendComment(): bool|string
    {
        $SchoolCourseModel = new SchoolCourseModel();
        $SchoolCourseModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'course_id|课程ID' => 'require',
                'chapter_id|章节ID' => 'require',
                'content|评论内容' => 'require'
            ]);
            $info = $SchoolCourseModel->find($param['course_id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['is_comment'] != 1) throw new \Exception('管理员已关闭留言功能！');
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $learningInfo = $SchoolCourseChapterLearningModel->where([
                ['uid', '=', $this->userData['id']],
                ['chapter_id', '=', $param['chapter_id']]
            ])->find();
            $learningInfo?->save([
                'is_comment' => 1
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $SchoolCourseChapterCommentModel = new SchoolCourseChapterCommentModel();
            $SchoolCourseChapterCommentModel->insert($param);
            $SchoolCourseModel->commit();
            return success();
        } catch (\Exception $e) {
            $SchoolCourseModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 保存心得
     * @return bool|string
     */
    public function saveLearning(): bool|string
    {
        $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
        $SchoolCourseChapterLearningModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'course_id|课程ID' => 'require',
                'chapter_id|章节ID' => 'require',
                'learning|心得' => 'require',
            ]);
            $SchoolCourseChapterCommentModel = new SchoolCourseChapterCommentModel();
            $is_comment = $SchoolCourseChapterCommentModel->where([
                ['uid', '=', $this->userData['id']],
                ['chapter_id', '=', $param['chapter_id']],
            ])->value('id');
            $info = $SchoolCourseChapterLearningModel->where([
                ['uid', '=', $this->userData['id']],
                ['chapter_id', '=', $param['chapter_id']]
            ])->find();
            if ($info){
                $info->save([
                    'learning' => $param['learning'],
                    'is_learning' => 1,
                    'is_comment' => $is_comment?1:0,
                    'up_time' => time()
                ]);
            }else{
                $SchoolCourseChapterLearningModel->insert([
                    'unit_id' => $this->userData['unit_id'],
                    'course_id' => $param['course_id'],
                    'chapter_id' => $param['chapter_id'],
                    'uid' => $this->userData['id'],
                    'is_learning' => 1,
                    'learning' => $param['learning'],
                    'is_comment' => $is_comment?1:0,
                    'up_time' => time(),
                    'time' => time()
                ]);
                $SchoolCourseChapterModel = new SchoolCourseChapterModel();
                $SchoolCourseChapterModel->where('id', '=', $param['chapter_id'])->inc('study_num')->save();
            }
            $study_num = $SchoolCourseChapterLearningModel->where('course_id','=',$param['course_id'])->column('uid');
            $SchoolCourseModel = new SchoolCourseModel();
            $SchoolCourseModel->where('id', '=', $param['course_id'])->update([
                'study_num' => count(array_unique($study_num))
            ]);
            $SchoolCourseChapterLearningModel->commit();
            return success();
        } catch (\Exception $e) {
            $SchoolCourseChapterLearningModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 提交测评任务
     * @return bool|string
     */
    public function SubmitEvaluationTask(): bool|string
    {
        $SchoolCourseChapterModel = new SchoolCourseChapterModel();
        $SchoolCourseChapterModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'question_answer|答案' => 'require',
                'finish_used_time|用户完成用时' =>  'require',
            ]);
            $chapter = $SchoolCourseChapterModel->find($param['id']);
            if (!$chapter) throw new \Exception('参数错误！');
            $SchoolCourseChapterLearningModel = new SchoolCourseChapterLearningModel();
            $info = $SchoolCourseChapterLearningModel->where([
                ['uid', '=', $this->userData['id']],
                ['chapter_id', '=', $param['id']]
            ])->find();
            if ($info && $info['is_finish'] == 1)  throw new \Exception('不可重复提交！');
            $SchoolService = new SchoolService($this->app);
            if (!$SchoolService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'chapter_id' => $param['id'],
                'rating_scale_id' => $chapter['rating_scale_id'],//量表ID
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ],9)) throw new \Exception('提交失败！');
            if ($info){
                $info->save([
                    'is_finish' => 1,
                    'result_id' => $SchoolService->ResultId,
                    'up_time' => time()
                ]);
            }else{
                $SchoolCourseChapterLearningModel->insert([
                    'unit_id' => $this->userData['unit_id'],
                    'course_id' => $chapter['course_id'],
                    'chapter_id' => $param['id'],
                    'uid' => $this->userData['id'],
                    'is_finish' => 1,
                    'result_id' => $SchoolService->ResultId,
                    'up_time' => time(),
                    'time' => time()
                ]);
            }
            $SchoolCourseChapterModel->commit();
            return success([
                'result_id' => $SchoolService->ResultId,
                'is_valid' => $SchoolService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $SchoolCourseChapterModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 结果详情
     * @return bool|string
     */
    public function reportInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSchoolEvaluationReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 结果详情2
     * @return bool|string
     */
    public function reportInfo2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSchoolReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}